package com.tcwlkj.uuService.ui.login;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.util.ArraySet;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.JsonObject;
import com.tcwlkj.uuService.MainActivity;
import com.tcwlkj.uuService.MyApp;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.DeviceModle;
import com.tcwlkj.uuService.model.LocationModel;
import com.tcwlkj.uuService.model.LoginModel;
import com.tcwlkj.uuService.model.TokenModel;
import com.tcwlkj.uuService.ui.BaseActivity;
import com.tcwlkj.uuService.utils.ChcheUtils;
import com.tcwlkj.uuService.utils.Const;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.ToastUtil;
import com.tcwlkj.uuService.utils.Tools;

import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import retrofit2.Call;
/**
 * Created by Administrator on 2017/10/9 0009.
 * 登录界面
 */

public class LoginActivity extends BaseActivity {
    @Bind(R.id.edit_name_login)
    EditText edit_name;
    @Bind(R.id.edit_ps_login)
    EditText edit_psw;
    @Bind(R.id.iv_old)
    ImageView iv_old;

    private LocationModel locationModel=new LocationModel(0d,0d);
    private LocationClient mLocationClient;//定位的客户端
    private MyLocationListener mMyLocationListener;//定位的监听器
    /**
     * 最新一次的经纬度
     */
    private double mCurrentLantitude;
    private double mCurrentLongitude;

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Set<String> tag = new ArraySet<String>();
            tag.add("330100");
            tag.add("杭州市");
            JPushInterface.setAliasAndTags(LoginActivity.this,"SD" +PreferencesUtils.getString(LoginActivity.this,"userID")+jpush,tag,mAliasCallback);

//            JPushInterface.setAlias(LoginActivity.this, "SD" +PreferencesUtils.getString(LoginActivity.this,"userID")+jpush, mAliasCallback);
//            Set<String> tag = new ArraySet<String>();
//            tag.add("330100");
//            tag.add("杭州市");
//            JPushInterface.setTags(LoginActivity.this, tag, mAliasCallback);
        }
    };
    private int jpush;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        Const.login=this;
        changeTitle("登录");
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                initMyLocation();
            }
        }, R.string.address, Manifest.permission.ACCESS_FINE_LOCATION);
        getToken("13-10-1-1");
    }

    boolean visible=true;
    @OnClick({R.id.btn_enter_login, R.id.tv_resetps_login, R.id.tv_register,R.id.iv_old})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_enter_login://登录
                Logion();
                break;
            case R.id.tv_resetps_login://忘记密码
                startActivity(ForgetPasswodActivity.class);
                break;
            case R.id.tv_register://注册账号
                startActivity(RegisterActivity.class);
                break;
            case R.id.iv_old:
                if(visible){
                    iv_old.setImageDrawable(getResources().getDrawable(R.mipmap.visible));
                    visible=false;
                    edit_psw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }else {
                    iv_old.setImageDrawable(getResources().getDrawable(R.mipmap.invisible));
                    visible=true;
                    edit_psw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
        }
    }
    private void Logion() {
        String name = edit_name.getText().toString().trim();
        String pwd = edit_psw.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtil.getInstance().show("请输入用户名");
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            ToastUtil.getInstance().show("请输入密码");
            return;
        }
        DeviceModle deviceModle = new DeviceModle("0", Tools.getDeviceModel(), Tools.getDeviceSystemVersion(), Tools.getVersion(baseContext),
                Tools.getIPAddress(baseContext), Tools.isNotificationEnabled(baseContext), Tools.getLocalMacAddressFromIp(baseContext), Tools.isLocationEnabled(baseContext));
        String str=Tools.javabeanToJson(locationModel);
        Call<CommonResponse<LoginModel>> httpResultCall = RetrofitUtils.getRequest(this, true)
                .Login(10002, name, pwd, 0, 13, Tools.javabeanToJson(locationModel), Tools.javabeanToJson(deviceModle));
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<LoginModel>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<LoginModel> commonResponse= (CommonResponse<LoginModel>) t;
                PreferencesUtils.putString(MyApp.getContext(),"userID",commonResponse.getData().getUserID()+"");
                PreferencesUtils.putString(MyApp.getContext(),"openid",commonResponse.getData().getOpenID()+"");
                PreferencesUtils.putString(MyApp.getContext(),"token",commonResponse.getData().getToken()+"");
                PreferencesUtils.putString(MyApp.getContext(),"JPushID",commonResponse.getData().getJPushID());
                PreferencesUtils.putBoolean(MyApp.getContext(),"Login",true);

                jpush = (int) (Math.random() * 1000);
                if (JPushInterface.isPushStopped(LoginActivity.this)) {
                    JPushInterface.resumePush(LoginActivity.this);
                }

                Set<String> tag = new ArraySet<String>();
                tag.add("330100");
                tag.add("杭州市");
                JPushInterface.setAliasAndTags(LoginActivity.this,"SD" + commonResponse.getData().getUserID()+ jpush,tag,mAliasCallback);
//
//                JPushInterface.setAlias(LoginActivity.this, "SD" + commonResponse.getData().getUserID()+ jpush, mAliasCallback);
//
//                JPushInterface.setTags(LoginActivity.this, tag, mAliasCallback);
                startActivity(MainActivity.class);
                finish();
            }
            @Override
            public void onFail(int code, String message) {
                if(code == 40104||code==40102||code==40100){
                    //验证码失效,进行激活
                    Logion();
                }else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }//登录

    //    在JPush服务stop状态下设置了tag或alias（6012）
    TagAliasCallback mAliasCallback = new TagAliasCallback() {
        public String logs;
        @Override
        public void gotResult(int code, String s, Set<String> set) {
            switch (code) {
                case 0://极光设置别名成功
                    SubmitJPushID();//提交极光ID
                    break;
                case 6002:
                default:
                    mHandler.sendEmptyMessageDelayed(1,6000);
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    System.out.println("===========>>>logs:" + logs);
                    break;
            }
        }
    };

    private void SubmitJPushID() {
        Call<CommonResponse> httpResultCall = RetrofitUtils.getRequest(this, false).SubmitJPushID("jpushid", PreferencesUtils.getString(MyApp.getContext(), "userID"), "SD" +PreferencesUtils.getString(LoginActivity.this,"userID")+jpush);
                httpResultCall.enqueue(new HttpCallBack<CommonResponse>() {
            @Override
            public void onSuccess(Object t) {
                Log.d("SubmitJPushID","极光注册成功");
            }
            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    SubmitJPushID();
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }
    public void getToken(String login) {
        Call<CommonResponse<TokenModel>> httpResultCall = RetrofitUtils.getRequest(this, false).gettoken(login);
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<TokenModel>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<TokenModel> commonResponse= (CommonResponse<TokenModel>) t;
                PreferencesUtils.putString(MyApp.getContext(),"openid",commonResponse.getData().getOpenid());
                PreferencesUtils.putString(MyApp.getContext(),"token",commonResponse.getData().getToken());
            }
            @Override
            public void onFail(int code, String message) {
                ToastUtil.getInstance().show(message);
            }
        });
    }//获取Token
    /**
     * 初始化定位相关代码
     */
    public void initMyLocation() {
        // 定位初始化
        mLocationClient = new LocationClient(getApplicationContext());
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);
        // 设置定位的相关配置
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式
        option.setIsNeedAddress(true);//返回的定位结果包含地址信息
        option.setCoorType("bd09ll"); // 设置坐标类型  只适用百度地图  火星坐标系
        mLocationClient.setLocOption(option);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }
    }
    /**
     * 实现实位回调监听
     */
    private String mCurrentAddress = "";

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null)
                return;
            /**
             * 最新一次的经纬度
             */
            mCurrentAddress = location.getAddrStr();
            mCurrentLantitude = location.getLatitude();
            mCurrentLongitude = location.getLongitude();
            // 第一次定位时，将地图位置移动到当前位置

            if (!TextUtils.isEmpty(mCurrentAddress)) {
                //mCurrentAddress = mCurrentAddress.substring(2, mCurrentAddress.length());
                locationModel.setLng(mCurrentLongitude);
                locationModel.setLat(mCurrentLantitude);
            } else {
                mCurrentAddress = "暂无位置信息";
                locationModel.setLng(0d);
                locationModel.setLat(0d);
            }
            Log.d("locationModel", Tools.javabeanToJson(locationModel));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
